package com.zdl.netutils.http;

import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 保留
 */
public class DownFileJava {

    /**
     * @param url              只是从url中获取
     * @param saveDir
     * @param response
     * @param downloadListener
     * @throws IOException
     */
    public static void writeResponseBodyToDisk(final String url, final String saveDir, Response<ResponseBody> response, DownloadListener downloadListener) throws IOException {
        InputStream is = null;
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream fos = null;
        ResponseBody body = response.body();
        // 储存下载文件的目录
        String saveFolder = isExistDir(saveDir);
//        String tempPath = saveFolder + File.separator + "temp_" + getNameFromUrl(url);
        String savePath = saveFolder + File.separator + getNameFromUrl(url);
//        String tempPath = saveFolder + File.separator + "temp_" + url;
        try {
            FileUtils.deleteFile(savePath);
            is = body.byteStream();
            long total = body.contentLength();
            File file = new File(savePath);
            fos = new FileOutputStream(file);
            long sum = 0;
            while ((len = is.read(buf)) != -1) {
                fos.write(buf, 0, len);
                sum += len;
                int progress = (int) (sum * 1.0f / total * 100);
                // 下载中
                downloadListener.onDownloading(progress);
            }
            fos.flush();
            // 下载完成
//            FileUtils.fileRename(tempPath, savePath);
            downloadListener.onDownloadSuccess(savePath);
        } catch (Exception e) {
            downloadListener.onDownloadFailed();
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
            }
        }
    }


    private static String isExistDir(String saveDir) throws IOException {
        // 下载位置
        File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
        if (!downloadFile.mkdirs()) {
            downloadFile.createNewFile();
        }
        String savePath = downloadFile.getAbsolutePath();
        return savePath;
    }


    public static String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }
}
